package org.lanqiao.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.lanqiao.tools.ResponseData;

import com.google.gson.Gson;

@WebFilter("/Servlet/*")
public class LoadFilter implements Filter {
	Gson gson = new Gson();
	ResponseData redata = new ResponseData();

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		res.setHeader("content-type", "text/html;chatset=utf-8");

		Object id = req.getSession().getAttribute("id");
		if (id != null) {

			chain.doFilter(req, res);
		} else {

			// 添加参数，允许访问我的域名跨域--->request2.getHeader("Origin")：谁访问的我
			res.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
			// 允许客户端携带验证信息
			res.setHeader("Access-Control-Allow-Credentials", "true");
			// 这个allow-headers要配为*，这样才能允许所有的请求头 ---
			res.setHeader("Access-Control-Allow-Headers", "*");
			// 允许的请求方式
			res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
			// 复杂请求多少秒内、不需要预请求（复杂请求：在请求的head里面添加参数）
			// res.setHeader("Access-Control-Max-Age", "100000");
			redata.setCode(3);
			redata.setMsg("请登录！！！");
			redata.setData("");

			response.getWriter().write(gson.toJson(redata));
		}

		System.out.println(req.getSession().getId() + "MyFilter/id=" + id);
	}

}
